# -*- coding: utf-8 -*-
"""
支付服务层

处理线上支付、线下支付和支付状态管理
"""
import uuid
import time
from datetime import datetime, timedelta
from typing import Dict, Any, Optional
from app.repositories.base_repository import BaseRepository
from app.models.order_status import OrderStatus, PaymentType, PaymentMethod, PaymentStatus


class PaymentService:
    """支付服务类"""
    
    def __init__(self):
        self.payment_repo = BaseRepository("payment_records")
        self.order_repo = BaseRepository("orders")
    
    def initiate_payment(self, order_id: str, payment_method: str, user_id: str) -> Dict[str, Any]:
        """发起支付"""
        try:
            # 获取订单信息
            print(f"查找订单: order_id={order_id}, user_id={user_id}")
            order = self.order_repo.find_by_id("order_id", order_id)
            print(f"查找结果: {order}")
            
            if not order:
                return {"success": False, "message": "订单不存在"}
            
            if order['customer_id'] != user_id:
                return {"success": False, "message": f"无权限操作该订单，订单客户:{order['customer_id']}, 当前用户:{user_id}"}
            
            # 兼容现有的订单状态值
            valid_statuses = [OrderStatus.SUBMITTED.value, 'pending', 'processing']
            if order['order_status'] not in valid_statuses:
                return {"success": False, "message": f"订单状态不正确，当前状态：{order['order_status']}"}
            
            # 判断支付类型
            payment_type = self._get_payment_type(payment_method)
            
            if payment_type == PaymentType.ONLINE:
                return self._process_online_payment(order, payment_method)
            else:
                return self._process_offline_payment(order, payment_method)
                
        except Exception as e:
            print(f"支付发起异常: {str(e)}")
            return {"success": False, "message": f"发起支付失败：{str(e)}"}
    
    def _process_online_payment(self, order: Dict[str, Any], payment_method: str) -> Dict[str, Any]:
        """处理线上支付"""
        try:
            # 创建支付记录
            payment_id = f"PAY{int(time.time())}{uuid.uuid4().hex[:8].upper()}"
            
            payment_record = {
                "payment_id": payment_id,
                "order_id": order['order_id'],
                "user_id": order['customer_id'],
                "payment_method": payment_method,
                "payment_type": PaymentType.ONLINE.value,
                "amount": order['final_amount'],
                "currency": "CNY",
                "status": PaymentStatus.PENDING.value,
                "created_time": datetime.now(),
                "expires_at": datetime.now() + timedelta(minutes=15)  # 15分钟过期
            }
            
            print(f"创建支付记录: {payment_record}")
            
            # 保存支付记录
            success = self.payment_repo.create(payment_record)
            print(f"支付记录创建结果: {success}")
            
            if not success:
                return {"success": False, "message": "创建支付记录失败"}
            
            # 模拟生成支付参数
            payment_data = self._generate_payment_data(payment_id, payment_method, order)
            
            return {
                "success": True,
                "message": "支付发起成功",
                "data": {
                    "payment_id": payment_id,
                    "payment_type": "online",
                    "payment_method": payment_method,
                    "payment_url": payment_data['payment_url'],
                    "payment_params": payment_data['payment_params'],
                    "expires_at": payment_record['expires_at'].isoformat(),
                    "amount": float(order['final_amount'])
                }
            }
            
        except Exception as e:
            print(f"线上支付处理异常: {str(e)}")
            return {"success": False, "message": f"线上支付处理失败：{str(e)}"}
    
    def _process_offline_payment(self, order: Dict[str, Any], payment_method: str) -> Dict[str, Any]:
        """处理线下支付"""
        try:
            # 创建支付记录
            payment_id = f"OFFLINE{int(time.time())}{uuid.uuid4().hex[:8].upper()}"
            
            payment_record = {
                "payment_id": payment_id,
                "order_id": order['order_id'],
                "user_id": order['customer_id'],
                "payment_method": payment_method,
                "payment_type": PaymentType.OFFLINE.value,
                "amount": order['final_amount'],
                "currency": "CNY",
                "status": PaymentStatus.PENDING.value,
                "created_time": datetime.now()
            }
            
            # 保存支付记录
            success = self.payment_repo.create(payment_record)
            if not success:
                return {"success": False, "message": "创建支付记录失败"}
            
            # 线下支付直接更新订单状态为已发货
            update_sql = """
                UPDATE orders SET 
                    order_status = %s,
                    payment_status = %s,
                    payment_method = %s,
                    updated_time = NOW()
                WHERE order_id = %s
            """
            self.order_repo.execute_custom_query(update_sql, [
                OrderStatus.SHIPPED.value,
                PaymentStatus.PENDING.value,
                payment_method,
                order['order_id']
            ], False)
            
            # 生成线下支付信息
            offline_info = self._generate_offline_payment_info(payment_method)
            
            return {
                "success": True,
                "message": "线下支付订单创建成功",
                "data": {
                    "payment_id": payment_id,
                    "payment_type": "offline",
                    "payment_method": payment_method,
                    "order_status": OrderStatus.SHIPPED.value,
                    "amount": float(order['final_amount']),
                    "payment_info": offline_info
                }
            }
            
        except Exception as e:
            return {"success": False, "message": f"线下支付处理失败：{str(e)}"}
    
    def handle_payment_success(self, payment_id: str, transaction_id: str = None) -> Dict[str, Any]:
        """处理支付成功回调"""
        try:
            # 获取支付记录
            payment = self.payment_repo.find_by_id("payment_id", payment_id)
            if not payment:
                return {"success": False, "message": "支付记录不存在"}
            
            if payment['status'] == PaymentStatus.PAID.value:
                return {"success": True, "message": "支付已完成"}
            
            # 更新支付记录
            update_payment_sql = """
                UPDATE payment_records SET 
                    status = %s,
                    transaction_id = %s,
                    paid_time = NOW(),
                    updated_time = NOW()
                WHERE payment_id = %s
            """
            self.payment_repo.execute_custom_query(update_payment_sql, [
                PaymentStatus.PAID.value,
                transaction_id,
                payment_id
            ], False)
            
            # 更新订单状态
            update_order_sql = """
                UPDATE orders SET 
                    order_status = %s,
                    payment_status = %s,
                    updated_time = NOW()
                WHERE order_id = %s
            """
            self.order_repo.execute_custom_query(update_order_sql, [
                OrderStatus.PAID.value,
                PaymentStatus.PAID.value,
                payment['order_id']
            ], False)
            
            return {
                "success": True,
                "message": "支付成功",
                "data": {
                    "order_id": payment['order_id'],
                    "payment_id": payment_id,
                    "transaction_id": transaction_id
                }
            }
            
        except Exception as e:
            return {"success": False, "message": f"支付成功处理失败：{str(e)}"}
    
    def handle_payment_failure(self, payment_id: str, error_msg: str = None) -> Dict[str, Any]:
        """处理支付失败"""
        try:
            # 获取支付记录
            payment = self.payment_repo.find_by_id("payment_id", payment_id)
            if not payment:
                return {"success": False, "message": "支付记录不存在"}
            
            # 更新支付记录
            update_payment_sql = """
                UPDATE payment_records SET 
                    status = %s,
                    error_msg = %s,
                    updated_time = NOW()
                WHERE payment_id = %s
            """
            self.payment_repo.execute_custom_query(update_payment_sql, [
                PaymentStatus.FAILED.value,
                error_msg,
                payment_id
            ], False)
            
            # 更新订单状态
            update_order_sql = """
                UPDATE orders SET 
                    order_status = %s,
                    payment_status = %s,
                    updated_time = NOW()
                WHERE order_id = %s
            """
            self.order_repo.execute_custom_query(update_order_sql, [
                OrderStatus.PAYMENT_FAILED.value,
                PaymentStatus.FAILED.value,
                payment['order_id']
            ], False)
            
            return {"success": True, "message": "支付失败状态已更新"}
            
        except Exception as e:
            return {"success": False, "message": f"支付失败处理失败：{str(e)}"}
    
    def upload_payment_receipt(self, order_id: str, receipt_url: str, user_id: str, 
                             notes: str = None) -> Dict[str, Any]:
        """上传支付回执"""
        try:
            # 获取订单信息
            order = self.order_repo.find_by_id("order_id", order_id)
            if not order:
                return {"success": False, "message": "订单不存在"}
            
            if order['customer_id'] != user_id:
                return {"success": False, "message": "无权限操作该订单"}
            
            if order['order_status'] != OrderStatus.RECEIPT_PENDING.value:
                return {"success": False, "message": "订单状态不正确"}
            
            # 创建回执记录
            receipt_id = f"RECEIPT{int(time.time())}{uuid.uuid4().hex[:8].upper()}"
            
            receipt_record = {
                "receipt_id": receipt_id,
                "order_id": order_id,
                "user_id": user_id,
                "receipt_url": receipt_url,
                "notes": notes,
                "status": "pending",  # pending, approved, rejected
                "created_time": datetime.now()
            }
            
            # 保存到支付回执表
            receipt_repo = BaseRepository("payment_receipts")
            success = receipt_repo.create(receipt_record)
            if not success:
                return {"success": False, "message": "保存回执记录失败"}
            
            # 更新订单状态
            update_sql = """
                UPDATE orders SET 
                    order_status = %s,
                    updated_time = NOW()
                WHERE order_id = %s
            """
            self.order_repo.execute_custom_query(update_sql, [
                OrderStatus.RECEIPT_UPLOADED.value,
                order_id
            ], False)
            
            return {
                "success": True,
                "message": "回执上传成功",
                "data": {
                    "receipt_id": receipt_id,
                    "order_id": order_id,
                    "receipt_url": receipt_url
                }
            }
            
        except Exception as e:
            return {"success": False, "message": f"上传回执失败：{str(e)}"}
    
    def get_payment_methods(self) -> Dict[str, Any]:
        """获取支付方式列表"""
        try:
            payment_methods = [
                {
                    "id": PaymentMethod.WECHAT.value,
                    "name": "微信支付",
                    "desc": "安全便捷的移动支付",
                    "icon": "wechat-pay",
                    "color": "#1aad19",
                    "type": PaymentType.ONLINE.value,
                    "available": True
                },
                {
                    "id": PaymentMethod.ALIPAY.value,
                    "name": "支付宝",
                    "desc": "快速安全支付",
                    "icon": "alipay",
                    "color": "#027aff",
                    "type": PaymentType.ONLINE.value,
                    "available": True
                },
                {
                    "id": PaymentMethod.OFFLINE_TRANSFER.value,
                    "name": "银行转账",
                    "desc": "通过银行转账付款",
                    "icon": "bank-transfer",
                    "color": "#8f8f94",
                    "type": PaymentType.OFFLINE.value,
                    "available": True
                },
                {
                    "id": PaymentMethod.OFFLINE_CASH.value,
                    "name": "现金支付",
                    "desc": "线下现金支付",
                    "icon": "cash",
                    "color": "#8f8f94",
                    "type": PaymentType.OFFLINE.value,
                    "available": True
                }
            ]
            
            return {
                "success": True,
                "data": payment_methods
            }
        except Exception as e:
            return {"success": False, "message": f"获取支付方式失败：{str(e)}"}
    
    def _get_payment_type(self, payment_method: str) -> PaymentType:
        """根据支付方式确定支付类型"""
        online_methods = [PaymentMethod.WECHAT.value, PaymentMethod.ALIPAY.value]
        return PaymentType.ONLINE if payment_method in online_methods else PaymentType.OFFLINE
    
    def _generate_payment_data(self, payment_id: str, payment_method: str, order: Dict[str, Any]) -> Dict[str, Any]:
        """生成支付参数（模拟）"""
        base_url = "http://localhost:8000"
        
        if payment_method == PaymentMethod.WECHAT.value:
            return {
                "payment_url": f"{base_url}/payment/wechat/{payment_id}",
                "payment_params": {
                    "appId": "wx_demo_app_id",
                    "timeStamp": str(int(time.time())),
                    "nonceStr": uuid.uuid4().hex[:16],
                    "package": f"prepay_id=prepay_{payment_id}",
                    "signType": "MD5",
                    "paySign": "demo_sign"
                }
            }
        elif payment_method == PaymentMethod.ALIPAY.value:
            return {
                "payment_url": f"{base_url}/payment/alipay/{payment_id}",
                "payment_params": {
                    "app_id": "alipay_demo_app_id",
                    "method": "alipay.trade.app.pay",
                    "charset": "utf-8",
                    "sign_type": "RSA2",
                    "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    "version": "1.0",
                    "biz_content": {
                        "out_trade_no": payment_id,
                        "total_amount": str(order['final_amount']),
                        "subject": f"订单支付-{order['order_no']}"
                    }
                }
            }
        else:
            return {
                "payment_url": f"{base_url}/payment/demo/{payment_id}",
                "payment_params": {}
            }
    
    def _generate_offline_payment_info(self, payment_method: str) -> Dict[str, Any]:
        """生成线下支付信息"""
        if payment_method == PaymentMethod.OFFLINE_TRANSFER.value:
            return {
                "bank_name": "中国工商银行",
                "account_name": "农药商城",
                "account_number": "6222000012345678901",
                "instructions": [
                    "请在转账备注中填写订单号",
                    "转账完成后请上传转账回执",
                    "我们将在收到回执后确认收款并完成订单"
                ]
            }
        elif payment_method == PaymentMethod.OFFLINE_CASH.value:
            return {
                "contact_phone": "400-123-4567",
                "contact_address": "农药商城线下门店",
                "instructions": [
                    "请联系客服安排线下付款",
                    "付款完成后请保留收据",
                    "如需开具发票请提前说明"
                ]
            }
        else:
            return {
                "instructions": ["请联系客服完成支付"]
            } 